#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: published_requirements.py
# Author: ChenChangSong
# Date: 2025-10-22

"""
功能描述: 获取已发布需求
"""
import requests
import json
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent.parent))
from comm.common_code import *
from comm.common_code import get_excel_data, logger, log_to_ui_info, log_to_ui_error

def req_get_published_requirements(tester,published_time):
    """
    获取已发布需求
    :param tester: 测试人员
    :param published_time: 需求实际发版时间
    :return: {ID1:需求名称1,ID2:需求名称2,...}
    """
    excel_data = get_excel_data()


    url = "https://www.tapd.cn/api/search_filter/search_filter/search"

    # 构建搜索条件数据
    search_data_dict = {
        "data": [
            {
                "fieldOption": "in",
                "fieldType": "user_chooser",
                "entity": "story",
                "fieldSubEntityType": "",
                "fieldSystemName": "测试人员",
                "fieldDisplayName": "测试人员",
                "selectOption": [],
                "value": "",
                "fieldIsSystem": "0",
                "id": "2"
            },
            {
                "fieldOption": "between",
                "fieldType": "dateinput",
                "entity": "story",
                "fieldSubEntityType": "",
                "fieldSystemName": "需求实际发版时间",
                "fieldDisplayName": "需求实际发版时间",
                "selectOption": [],
                "value": published_time,
                "fieldIsSystem": "0",
                "id": "3"
            },
            {
                "id": "4",
                "fieldLabel": "测试人员",
                "fieldOption": "in",
                "fieldType": "user_chooser",
                "fieldSystemName": "测试人员",
                "value": tester,
                "fieldIsSystem": "0",
                "entity": "story"
            }
        ],
        "optionType": "AND",
        "needInit": "1"
    }
    search_data = json.dumps(search_data_dict)
    
    headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Cookie': excel_data['Cookie'],
    'Origin': 'https://www.tapd.cn',
    'Referer': 'https://www.tapd.cn/tapd_fe/worktable/search?queryToken=65467117fa6fb44b19bba1bffa928959',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.577.400 QQBrowser/19.8.6823.400',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"'
    }

    requirement_list = {}
    requirements_dict = {}
    page = 1
    has_more_data = True
    
    while has_more_data:
        logger.info(f"正在获取第 {page} 页的需求数据...")
        
        # 构建当前页的请求参数
        payload = json.dumps({
        "workspace_ids": f"{excel_data['项目ID']}",
        "search_data": "{\"data\":[{\"id\":\"1\",\"fieldDisplayName\":\"处理人\",\"fieldIsSystem\":\"0\",\"fieldOption\":\"in\",\"fieldSystemName\":\"测试人员\",\"fieldType\":\"user_chooser\",\"selectOption\":[],\"value\":\"" + tester + ";\",\"entity\":\"story\",\"fieldLabel\":\"测试人员\"},{\"id\":\"3\",\"fieldLabel\":\"需求实际发版时间\",\"fieldOption\":\"between\",\"fieldType\":\"dateinput\",\"fieldSystemName\":\"需求实际发版时间\",\"value\":\"" + published_time + "\",\"fieldIsSystem\":\"0\",\"entity\":\"story\"}],\"optionType\":\"AND\",\"needInit\":\"1\"}",
        "obj_type": "story",
        "search_type": "advanced",
        "page": page,
        "perpage": "100",
        "block_size": 50,
        "parallel_token": "",
        "order_field": "created",
        "order_value": "desc",
        "show_fields": [],
        "extra_fields": [],
        "display_mode": "list",
        "version": "1.1.0",
        "only_gen_token": 0,
        "exclude_workspace_configs": [],
        "from_pro_dashboard": 1,
        "hide_not_match_condition_node": 0,
        "hide_not_match_condition_sub_node": 0,
        "block_type": "",
        "dsc_token": "Mg8ad2wfImzG1Z2M"
        })
        
        response_code, response = api_request(method="POST", url=url, headers=headers, data=payload)

        if response_code == 200:
            logger.info(f"获取第 {page} 页已发布需求 - 成功")
            
            # 检查响应中是否有数据
            if 'data' in response and 'list' in response['data']:
                requirement_list = response['data']['list']
                logger.info(f"第 {page} 页已发布需求列表数量: {len(requirement_list)}")
                
                # 如果当前页没有数据，结束循环
                if not requirement_list:
                    logger.info(f"第 {page} 页没有数据，已获取全部需求")
                    has_more_data = False
                else:
                    # 处理当前页的数据
                    for item in requirement_list:
                        if 'id' in item and 'name' in item:
                            # 检查是否为父需求，是父需求则跳过，不加入需求列表
                            if item['status_alias'] == "父需求":
                                continue
                            requirement_id = item['id']
                            requirement_name = item['name']
                            requirements_dict[requirement_id] = requirement_name
                    
                    # 增加页码，继续获取下一页
                    page += 1
            else:
                logger.warning(f"第 {page} 页响应格式不正确，缺少data.list字段")
                has_more_data = False
        else:
            logger.error(f"获取第 {page} 页已发布需求 - 失败，错误码: {response_code}")
            # 可以选择是否在错误时继续尝试，这里选择停止
            has_more_data = False
    
    # 所有页面获取完成后，输出汇总信息
    logger.info(f"已发布需求总数: {len(requirements_dict)}")
    if requirements_dict:
        logger.info(f"获取已发布需求 - 所有需求:\n {requirements_dict}")
    else:
        logger.warning(f"未获取到任何已发布需求")
    return requirements_dict

if __name__ == "__main__":
    req_get_published_requirements(tester='陈昌松',published_time='2025-11-02 00:00,2025-11-02 23:59')
    # req_get_published_requirements(tester='李玉娇',published_time='2025-10-03 00:00,2025-11-03 23:59')